<template>
  <div>
    <Card title="新增返现活动信息" :bordered="false" dis-hover class="ivu-mt">
      <Form
        ref="formData"
        :model="formData"
        :rules="formDataRules"
        :label-width="220"
      >
        <Row>
          <Col
            span="18"
            offset="1"
            v-for="(item, index) in copyFormData"
            :key="index"
          >
            <component
              :itemData="item.data"
              :formData.sync="formData"
              v-bind:is="item.fileName"
              @handleChangeFormData="handleChangeFormData"
            ></component>
          </Col>
          <Col span="18" offset="3">
            <FormItem>
              <Button
                type="primary"
                :loading="sLoading"
                @click="handleSubmit('formData')"
                >提交</Button
              >
              <Button @click="handleReset('formData')" class="ivu-ml-8"
                >清空</Button
              >
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Card>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import forms from '@/mixins/dynamicFormAdd'; // 混入通用代码
import qwSelectTree from '@/components/common/formItem/qwSelectTree'; // selectTree组件
import qwInput from '@/components/common/formItem/qwInput'; // input组件
import qwSelect from '@/components/common/formItem/qwSelect'; // select组件
import qwDatePicker from '@/components/common/formItem/qwDatePicker'; // 时间组件
import qwUpload from '@/components/common/formItem/qwUpload'; // upload组件
import qwCascader from '@/components/common/formItem/qwCascader'; // 级联组件
import qwRadio from '@/components/common/formItem/qwRadio'; // 单选组件
import qwCheckbox from '@/components/common/formItem/qwCheckbox'; // 多选组件
import qwQuill from '@/components/common/formItem/qwQuill'; // 多选组件

export default {
  mixins: [forms],
  components: {
    qwSelectTree,
    qwInput,
    qwDatePicker,
    qwSelect,
    qwUpload,
    qwCascader,
    qwRadio,
    qwCheckbox,
    qwQuill
  },
  data () {
    // sPriceCheck
    const priceCheck = (rule, value, callback) => {
      let reg = /(^[1-9]{1}\d{0,5}$)|(^[0-9]{1,6}[\\.]{1}[0-9]{1,2}$)/;
      if (value === '') {
        callback(new Error('请填写金额'));
      } else if (!reg.test(value)) {
        callback(
          new Error('请输入正确的金额，整数位最多六位，小数位最多保留两位')
        );
      } else {
        callback();
      }
    };
    // 时间范围校验
    const validateValidStart = (rule, value, callback) => {
      let valueTime = new Date(value).getTime();
      let nowTime = new Date(this.getNowTime()).getTime();
      if (valueTime < nowTime) {
        callback(new Error('开始时间不得小于当前时间'));
      } else {
        callback();
      }
    };
    const validateValidEnd = (rule, value, callback) => {
      let endTime = new Date(value).getTime();
      let beginTime = new Date(this.formData.startTime);
      if (endTime < beginTime) {
        callback(new Error('结束时间不得小于开始时间'));
      } else {
        callback();
      }
    };
    return {
      formDataRules: {
        cashName: [
          { required: true, message: '返现活动名称', trigger: 'change' },
          {
            type: 'string',
            min: 2,
            max: 25,
            message: '返现活动名称在2-25字符之间',
            trigger: 'blur'
          }
        ],
        totalMoney: [
          { required: true, message: '请输入返现活动总金额', trigger: 'blur' },
          { required: true, validator: priceCheck, trigger: 'blur' }
        ],
        maxMoney: [
          {
            required: true,
            message: '请输入单笔订单最高返现金额',
            trigger: 'blur'
          },
          { required: true, validator: priceCheck, trigger: 'blur' }
        ],
        cashBackMoney: [
          { required: true, message: '请输入返现条件', trigger: 'blur' },
          { required: true, validator: priceCheck, trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' },
          { validator: validateValidStart, trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' },
          { validator: validateValidEnd, trigger: 'change' }
        ]
      }
    };
  },
  methods: {
    // 提交
    handleSubmit (name) {
      // if (!Number(this.formData.totalMoney)) {
      //     this.$Message.error('返现活动金额输入不合法')
      //     return;
      // }
      // if (!Number(this.formData.maxMoney)) {
      //     this.$Message.error('单笔订单最高返现金额输入不合法')
      //     return;
      // }
      // if (!Number(this.formData.cashBackMoney)) {
      //     this.$Message.error('返现条件输入不合法')
      //     return;
      // }

      // if (this.formData.endTime < this.formData.startTime) {
      //     this.$Message.error('结束时间需要大于开始时间');
      //     return
      // }
      // if (this.formData.totalMoney < 0 || this.formData.totalMoney > 99999999) {
      //     this.$Message.error('请检查返现活动金额输入内容是否正确');
      //     return
      // }
      // if (this.formData.maxMoney < 0 || this.formData.maxMoney > 99999999) {
      //     this.$Message.error('请检查单笔订单最高返现金额输入内容是否正确');
      //     return
      // }
      // if (this.formData.cashBackMoney < 0 || this.formData.cashBackMoney > 99999999) {
      //     this.$Message.error('请检查返现条件输入内容是否正确');
      //     return
      // }
      if (Number(this.formData.maxMoney) > Number(this.formData.totalMoney)) {
        this.$Message.error('单笔订单最高返现金额不可大于返现活动总金额');
        return;
      }
      if (
        Number(this.formData.cashBackMoney) > Number(this.formData.totalMoney)
      ) {
        this.$Message.error('返现条件不可大于返现活动总金额');
        return;
      }
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.sLoading) {
            return false;
          }
          this.sLoading = true;
          let data = this.formData;
          // 开始请求会员信息
          ApiRequest(
            this.requestApi.addDataInfo.url,
            this.requestApi.addDataInfo.type,
            data
          ).then(res => {
            if (res.retStatus === '1') {
              this.$Message.success('操作成功!');
              this.$router.go(-1);
            }
            this.sLoading = false;
          });
        } else {
          this.$Message.error('请完善信息!');
        }
      });
    },
    // 获取初始配置信息
    getConfigData () {
      this.pagePath = this.$route.path;
      let dynamicData = require('./configjs/returnActivityAdd').default;
      this.requestApi = dynamicData.requestApi; // 页面所需接口集合
      this.$set(this.$data, 'dynamicData', dynamicData);

      // copy 一份数据 方便清空表单数据
      let copyFormData = JSON.parse(JSON.stringify(this.dynamicData.formData));
      let copyFormDataRules = JSON.parse(
        JSON.stringify(this.dynamicData.formDataRules)
      );
      // 传给子组件的数据
      this.copyFormData = copyFormData;
      this.copyFormDataRules = copyFormDataRules;

      // 动态添加formData 提交数据内容
      copyFormData.forEach(item => {
        const obj = item.data;
        let name = '';
        let val = '';
        if (obj.type === 'inputRange' || obj.type === 'inputNumberRange') {
          obj.valueArr.forEach(item => {
            name = item.name;
            val = item.value;
            this.$set(this.formData, name, val);
          });
        } else {
          name = obj.name;
          val = obj.value;
          this.$set(this.formData, name, val);
        }
      });
    },
    getNowTime () {
      let date = new Date();
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? '0' + MM : MM;
      let d = date.getDate();
      d = d < 10 ? '0' + d : d;
      let h = date.getHours();
      h = h < 10 ? '0' + h : h;
      let m = date.getMinutes();
      m = m < 10 ? '0' + m : m;
      let s = date.getSeconds();
      s = s < 10 ? '0' + s : s;
      return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
    }
  }
};
</script>
<style lang="less" scoped>
</style>
